package com.ddc.study.feature.main;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.ddc.study.R;
import com.ddc.study.base.BaseActivity;
import com.ddc.study.base.BaseApplication;
import com.ddc.study.databinding.ActivityMainBinding;
import com.ddc.study.entity.User;
import com.ddc.study.feature.collect.CollectActivity;
import com.ddc.study.feature.friend.FriendSiteActivity;
import com.ddc.study.feature.login.LoginActivity;
import com.ddc.study.feature.main.home.HomeFragment;
import com.ddc.study.feature.main.navigation.NavigationFragment;
import com.ddc.study.feature.main.project.ProjectFragment;
import com.ddc.study.feature.main.tree.TreeFragment;
import com.ddc.study.feature.query.QueryActivity;
import com.ddc.study.feature.settings.SettingsActivity;
import com.ddc.study.user.UserManager;
import com.ddc.study.util.Log;
import com.google.android.material.navigation.NavigationView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.view.GravityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

/**
 * Created on 2018/3/30.
 *
 * @author lshun
 * @version 1.0
 */
public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private static final int REQUEST_CODE_LOGIN = 0x01;
    private static final int REQUEST_CODE_COLLECT = 0x02;

    private UserManager.UserObserver mObserver;

    private Fragment mHomeFragment;
    private long mLastTime;
    private boolean mNightMode;//是否启用了夜间模式

    private ActivityMainBinding mBinding;

    @Override
    protected int getLayoutRes() {
        return -1;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        setSupportActionBar(mBinding.include.toolbar);

        mBinding.viewPager2.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                switch (position) {
                    case 0:
                        mHomeFragment = new HomeFragment();
                        return mHomeFragment;
                    case 1:
                        return new TreeFragment();
                    case 2:
                        return new NavigationFragment();
                    case 3:
                        return new ProjectFragment();
                    default:
                        return new Fragment();
                }
            }

            @Override
            public int getItemCount() {
                return 4;
            }
        });
        mBinding.viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.e(TAG, "onPageSelected -> " + position);
                Menu menu = mBinding.bottomNavigationView.getMenu();
                if (position < 0 || position >= menu.size()) return;
                mBinding.bottomNavigationView.setSelectedItemId(menu.getItem(position).getItemId());
            }
        });
        mBinding.viewPager2.setOffscreenPageLimit(1);

        mBinding.bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            Menu menu = mBinding.bottomNavigationView.getMenu();
            for (int i = 0, len = menu.size(); i < len; i++) {
                if (menu.getItem(i).getItemId() == item.getItemId()) {
                    mBinding.viewPager2.setCurrentItem(i);
                    return true;
                }
            }
            return false;
        });

        mBinding.navView.setNavigationItemSelectedListener(this);

        final TextView tvUsername = mBinding.navView.getHeaderView(0).findViewById(R.id.tv_username);
        tvUsername.setOnClickListener(v -> {
            if (v.getTag() == null) {
                Intent i = new Intent(MainActivity.this, LoginActivity.class);
                startActivityForResult(i, REQUEST_CODE_LOGIN);
            }
        });

        updateUserInfo(((BaseApplication) getApplication()).getUser());

        mObserver = user -> runOnUiThread(() -> {
            Log.e(TAG, "onUserChanged -> " + user);
            updateUserInfo(user);
        });

        observe(mObserver);

        mBinding.tvNightMode.setOnClickListener(v -> {
            if (mNightMode) {//关闭夜间模式
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                showToast("夜间模式已关闭");
                mNightMode = false;
            } else {//打开夜间模式
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                showToast("夜间模式已打开");
                mNightMode = true;
            }
        });

        mBinding.tvSettings.setOnClickListener(v -> {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
        });
    }

    private void updateUserInfo(@Nullable User user) {
        TextView tvUsername = mBinding.navView.getHeaderView(0).findViewById(R.id.tv_username);
        if (user != null) {
            tvUsername.setTag(user.username);
            tvUsername.setText(user.username);
            mBinding.navView.getMenu().findItem(R.id.nav_collection_list).setVisible(true);
        } else {
            //未登录隐藏部分菜单
            tvUsername.setText(R.string.un_login);
            tvUsername.setTag(null);
            mBinding.navView.getMenu().findItem(R.id.nav_collection_list).setVisible(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeObserver(mObserver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_LOGIN:
                if (resultCode != RESULT_OK) return;
                break;
            case REQUEST_CODE_COLLECT:
                mHomeFragment.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_search) {
            startActivity(new Intent(this, QueryActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (mBinding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            long now = System.currentTimeMillis();
            if (now - mLastTime > 2000) {
                mLastTime = now;
                showToast("再按一次退出");
            } else {
                mLastTime = 0;
                moveTaskToBack(true);
            }
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.nav_friend_site:
                startActivity(new Intent(this, FriendSiteActivity.class));
                break;
            case R.id.nav_collection_list:
                if (isLoggedIn()) {
                    Intent intent = new Intent(this, CollectActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_COLLECT);
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            default:
                showToast(String.format("【%s】功能暂未实现", menuItem.getTitle()));
                break;
        }
        return false;
    }
}
